package henu.graduation_design.adapter;

import henu.graduation_design.onlineshop.R;
import henu.graduation_design.util.AsyncImageLoader;

import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CartAdapter extends BaseAdapter {
	private Context context;
	private List<HashMap<String, Object>> list;
	private AsyncImageLoader asyncImageLoader = new AsyncImageLoader();

	public CartAdapter(Context context, List<HashMap<String, Object>> list) {
		this.context = context;
		this.list = list;
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final ProductHolder holder;
		convertView = LayoutInflater.from(context).inflate(
				R.layout.listview_cart_cell, null);
		holder = new ProductHolder();
		holder.imageView = (ImageView) convertView
				.findViewById(R.id.cart_image);
		holder.nameTextView = (TextView) convertView
				.findViewById(R.id.cart_name);
		holder.priceTextView = (TextView) convertView
				.findViewById(R.id.cart_price);
		holder.originalpriceTextView = (TextView) convertView
				.findViewById(R.id.cart_original_price);

		final HashMap<String, Object> currentItem = list.get(position);

		holder.nameTextView.setText(currentItem.get("name").toString());
		holder.priceTextView.setText("￥"+currentItem.get("price").toString());
		loadImage(currentItem.get("imageUri").toString(), holder.imageView);
		if (!currentItem.get("price").toString()
				.equals(currentItem.get("OriginalPrice").toString())) {
			holder.originalpriceTextView.setText("￥"+currentItem.get(
					"OriginalPrice").toString());
			holder.originalpriceTextView.getPaint().setFlags(
					Paint.STRIKE_THRU_TEXT_FLAG);
		}
		return convertView;
	}

	private void loadImage(final String url, final ImageView imageView) {
		// 如果缓存过就会从缓存中取出图像，ImageCallback接口中方法也不会被执行
		Drawable cacheImage = asyncImageLoader.loadDrawable(url,
				new AsyncImageLoader.ImageCallback() {
					// 请参见实现：如果第一次加载url时下面方法会执行
					public void imageLoaded(Drawable imageDrawable) {
						imageView.setImageDrawable(imageDrawable);
					}
				});
		if (cacheImage != null) {
			imageView.setImageDrawable(cacheImage);
		}
	}

	private class ProductHolder {
		private ImageView imageView;
		private TextView nameTextView;
		private TextView priceTextView;
		private TextView originalpriceTextView;
	}
}
